import json
import os
import datetime
from PIL import Image
from django.db.models import Q
from django.db.models.fields.files import FieldFile
from django.http import HttpResponse
from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination
from rest_framework.filters import OrderingFilter, SearchFilter

from appBackend.models import WallPaper
from appBackend.serializers import WallPaperSerializer
from siliTech import settings
from django.forms.models import model_to_dict
import logging

logger = logging.getLogger("log")


class MyPageNumberPagination(PageNumberPagination):
    page_size = 10
    page_query_param = 'page'
    page_size_query_param = 'size'
    max_page_size = 30


class WallPaperViewSet(viewsets.ModelViewSet):
    queryset = WallPaper.objects.all()
    serializer_class = WallPaperSerializer
    pagination_class = MyPageNumberPagination  # 添加个分页器分页查询

    filter_backends = [OrderingFilter, SearchFilter]
    search_fields = ['catalogue']  # 条件查询的字段，可以添加多个字段，通过关键字查询


def get_image_original(request):
    image_file_name = request.GET.get("filename")
    if not image_file_name:
        return HttpResponse(image_file_name)

    image_file_path = os.path.join(settings.BASE_DIR, 'media', 'WallPapers', 'original', image_file_name)
    if os.path.exists(image_file_path):
        return HttpResponse(open(image_file_path, 'rb').read(), content_type='image/jpeg')


def get_image_thumb(request):
    image_file_name = request.GET.get("filename")
    if not image_file_name:
        return HttpResponse(image_file_name)

    thumb_path = os.path.join(settings.BASE_DIR, 'media', 'WallPapers', 'thumb')
    if not os.path.exists(thumb_path):
        os.makedirs(thumb_path)

    image_thumb_path = os.path.join(settings.BASE_DIR, 'media', 'WallPapers', 'thumb', image_file_name)
    if not os.path.exists(image_thumb_path):

        image_file_path = os.path.join(settings.BASE_DIR, 'media', 'WallPapers', 'original', image_file_name)

        logger.info(f"创建缩略图:{image_file_path}")

        image = Image.open(image_file_path)
        image.thumbnail((500, 500))
        image.save(image_thumb_path)

        return HttpResponse(open(image_thumb_path, 'rb').read(), content_type='image/jpeg')
    else:
        return HttpResponse(open(image_thumb_path, 'rb').read(), content_type='image/jpeg')


class DateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime('%Y-%m-%d')
        elif isinstance(obj, FieldFile):
            return str(obj)

        return json.JSONEncoder.default(self, obj)


def get_most_beautiful_place(request):
    """
    获取最美的地方的壁纸
    """
    queryset = WallPaper.objects.filter(~Q(info__icontains="N/A"))
    dict_list = [model_to_dict(obj) for obj in queryset]
    return HttpResponse(json.dumps(dict_list, cls=DateTimeEncoder), content_type='application/json')


def get_recently_wallpaper(request):
    queryset = WallPaper.objects.all().order_by('-uploadTime')[:20]
    print(queryset)
    dict_list = [model_to_dict(obj) for obj in queryset]
    return HttpResponse(json.dumps(dict_list, cls=DateTimeEncoder), content_type='application/json')
